<template>
  <el-dialog
    title="共享管理"
    :close-on-click-modal="true"
    :visible.sync="visible"
    class="jsbos-dialog jsbos-dialog_center transfer-dialog"
    lock-scroll
    width="500px"
    :modal="false"
  >
    <el-form
      ref="elForm"
      :model="dataForm"
      :rules="rules"
      size="small"
      label-width="100px"
      label-position="right"
      v-loading="loading"
    >
      <el-col :span="24">
        <el-form-item label="截止日期" prop="endTime">
          <el-date-picker
            v-model="dataForm.endTime"
            placeholder="请选择"
            clearable
            :style="{ width: '100%' }"
            type="datetime"
            :picker-options="pickerOption"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="timestamp"
            :editable="false"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="共享类型" prop="shareType">
          <el-radio
            v-model="dataForm.shareType"
            label="1"
            @change.native="chooseUser"
            >内部</el-radio
          >
          <el-radio v-model="dataForm.shareType" label="2">对外</el-radio>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item
          label="共享人员"
          prop="shareUserName"
          v-if="dataForm.shareType == '1' && dataForm.shareUserName"
        >
          <span>
            {{ dataForm.shareUserName }}
          </span>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item
          label="认证方式"
          prop="password"
          v-if="dataForm.shareType == '2'"
        >
          <el-radio v-model="dataForm.password" label="1">无</el-radio>
          <el-radio v-model="dataForm.password" label="2">口令</el-radio>
        </el-form-item>
      </el-col>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{
        $t("common.cancelButton")
      }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{
        $t("common.confirmButton")
      }}</el-button>
    </span>
    <userBox
      v-if="userBoxVisible"
      ref="userBox"
      @getShareUserId="getShareUserId"
    />
  </el-dialog>
</template>

<script>
import {
  ShareCreate,
  ShareUserList,
  Download,
  getShareEntityById,
  shareUpdate,
} from "@/api/extend/document";
import { getUserInfoList } from "@/api/permission/user";
import userTransfer from "@/components/user-transfer";
import userBox from "./UserBox";
import define from "@/utils/define";
import { Loading } from "element-ui";
import { isEmpty } from "@/utils/isEmpty";
export default {
  components: { userTransfer, userBox },
  data() {
    return {
      pickerOption: {
        disabledDate: (time) => {
          return Date.now() - 3600 * 1000 * 24 > time.getTime();
        },
      },
      loading: false,
      visible: false,
      userBoxVisible: false,
      documentId: "",
      treeData: [],
      checkedKeys: [],
      dataForm: {
        password: "2",
        shareType: "1",
      },
      rules: {
        shareType: [
          { required: true, message: "分享类型不能为空！", trigger: "change" },
        ],
        password: [
          { required: true, message: "口令类型不能为空！", trigger: "change" },
        ],
      },
      url: "",
      shareUserId: "",
      exposeLink: "",
    };
  },
  watch: {
    dataForm: {
      deep: true,
      handler(newValue, oldValue) {
        if (newValue.shareType == "2") {
          this.dataForm.password = "2";
        } else {
          this.dataForm.password = "";
        }
      },
    },
  },
  methods: {
    init(documentId, shareId) {
      this.loading = true;
      if (!documentId) return;
      this.documentId = documentId;
      this.visible = true;
      this.dataForm = {
        password: "2",
        shareType: "2",
      };

      //有shareId则是编辑
      if (shareId) {
        this.loading = true;
        getShareEntityById(shareId).then((res) => {
          let data = res.data;
          if (!!data.password && data.password.length > 4) {
            data.password = "2";
          }
          data.updateShareDocument = true;

          this.dataForm = data;
          this.loading = false;
        });
      }
      this.loading = false;
      this.previewFile(documentId);
    },
    getShareUserId(userIds) {
      this.checkedKeys = userIds;
      getUserInfoList(this.checkedKeys).then((res) => {
        this.dataForm.shareUserName = res.data.list
          .map((o) => o.realName)
          .join(",");
      });
    },
    chooseUser() {
      this.userBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.userBox.init(this.documentId);
      });
    },
    async dataFormSubmit() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          if (
            !this.checkedKeys.length &&
            this.dataForm.shareType == "1" &&
            !this.dataForm.updateShareDocument
          ) {
            this.$message({
              message: "请选择共享人员",
              type: "error",
              duration: 1000,
            });
            return;
          }
          this.dataForm.shortLink = this.url;
          if (
            !this.dataForm.updateShareDocument ||
            (this.dataForm.updateShareDocument &&
              this.dataForm.shareType == "1")
          ) {
            this.dataForm.userId = this.checkedKeys.join(",");
          }
          this.request();
        }
      });
    },

    request() {
      if (this.dataForm.updateShareDocument) {
        shareUpdate(this.dataForm.id, this.dataForm).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1500,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh");
            },
          });
        });
      } else {
        this.dataForm.exposeLink = this.exposeLink;
        ShareCreate(this.documentId, this.dataForm).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1500,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh");
            },
          });
        });
      }
    },
    previewFile(id) {
      Download(id).then((res) => {
        let url;
        const Base64 = require("js-base64").Base64;
        if (process.env.NODE_ENV === "development") {
          //对外暴露链接
          this.exposeLink = define.localUrl + "/#/viewDocument";
          url =
            define.localUrl + res.data.url + "&fullfilename=" + res.data.name;
          url =
            define.previewLocalUrl +
            "FileServer/onlinePreview?url=" +
            encodeURIComponent(Base64.encode(url));
        } else {
          //对外暴露链接
          this.exposeLink = define.serverFrontUrl + "/#/viewDocument";
          url =
            define.serverOnlineUrl +
            res.data.url +
            "&fullfilename=" +
            res.data.name;
          url =
            define.previewServerUrl +
            "onlinePreview?url=" +
            encodeURIComponent(Base64.encode(url));
        }
        this.url = url;
      });
    },
  },
};
</script>
